// pages/directBuy/directBuy.js
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    radioItems: [
      { name: '2', value: '在线支付', checked: 'true' },
    ],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    app.showShareMenus();
    this.setData({
      imageUrl: app.globalData.imageUrl
    })
    // console.log( wx.getStorageSync('cartLists'))

  },
  onShareAppMessage: function (res) {
    return {
      title: '成都品牌服饰批发零售定制',
      path: '/pages/homepage/homepage?id=' + wx.getStorageSync("userid"),
    }
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    var cartLists = wx.getStorageSync('cartLists');//从本地缓存获取购物车的商品信息
    //console.log(cartLists)
    if (cartLists == "" || isNaN(cartLists[0].totalPrices)) {//判断购物车是否有东西，没有就显示没有，有就显示有的|
      this.setData({//隐藏信息
        hasCarts: true,
        noCarts: false
      })
    } else {//如果购物车有物品就遍历他，在把价格算出来
      this.setData({//显示信息
        hasCarts: false,
        noCarts: true
      })
      for (var y in cartLists) {//遍历购物车
        cartLists[y].totalPrices = parseFloat(cartLists[y].unitPrice * cartLists[y].quantity).toFixed(2)//让购物车里的单价乘以数量，得到单件商品的总价
      }

      this.setData({ cartLists: cartLists });//同步显示到页面
      wx.setStorageSync('cartLists', cartLists)//同步储存在本地以备购买时调用
      var totalMoneyArr = [];
      for (var index in this.data.cartLists) {//计算总的价格
        totalMoneyArr.push(parseFloat(this.data.cartLists[index].quantity * this.data.cartLists[index].unitPrice).toFixed(2));
      }
      var totalMoney = totalMoneyArr.reduce(function (a, b) {
        return (parseFloat(a) + parseFloat(b)).toFixed(2);
      });
      this.setData({
        totalMoney: (parseFloat(totalMoney)).toFixed(2),
      })

      wx.setStorageSync('totalMoney', that.data.totalMoney)//储存在本地以备购买时调用
    }
    if (wx.getStorageSync('userAddress')) {
      var userAddress = wx.getStorageSync('userAddress');
       this.setData({
         inputAddress: userAddress.address,
         inputPhone: userAddress.phone,
         inputUser: userAddress.name,
       })
     }
    wx.getSystemInfo({//获取滑块的高宽
      success: function (res) {
        that.setData({
          winWidth: res.windowWidth,
          winHeight: res.windowHeight
        });
      }
    });
  },

  chooseaddress: function () {
    var that = this;
    wx.chooseAddress({
      success: function (res) {
        that.setData({
          inputUser: res.userName,
          inputPhone: res.telNumber,
          inputAddress: res.provinceName + res.cityName + res.countyName + res.detailInfo + '',
        })
        var address = {
          name: res.userName,
          phone: res.telNumber,
          address: res.provinceName + res.cityName + res.countyName + res.detailInfo,
        }
        wx.setStorageSync('userAddress', address)
      }, fail: function (e) {
      }
    })
  },
  addQuantity: function (e) {//增加单个商品数量
    this.changeCartItemQuantity('+', e)
  },

  minusQuantity: function (e) {//减少单个商品数量
    this.changeCartItemQuantity('-', e)
  },

  changeCartItemQuantity: function (op, e) {//改变单个商品数量
    var that = this;
    var cartLists = this.data.cartLists//找到储存在本地购物车的商品信息
    var cart = cartLists.filter(function (ele) {//过滤出点击加减的商品在本地储存的唯一商品ID
      return ele.productId === e.currentTarget.dataset.id

    })[0]
    if (op === '-' && cart.quantity > 1) {//如果符号为－，则商品数量减一
      cart.quantity -= 1;
      cart.totalPrices = parseFloat(cart.quantity * cart.unitPrice).toFixed(2)
    } else if (op === '+') {//如果符号为+，则商品数量加一
      if (cart.quantity == cart.repertory) {//如果增加的数量大于库存，则取消增加；
        wx.showToast({
          title: "库存不足",
          icon: "loading"
        })
      } else {
        cart.quantity += 1;
      }
      cart.totalPrices = parseFloat(cart.quantity * cart.unitPrice).toFixed(2)
    } else if (op === '-' && cart.quantity == 1) {
      cart.quantity -= 1;
      cart.totalPrices = parseFloat(cart.quantity * cart.unitPrice).toFixed(2);
      //  console.log(cart);
    }
    for (var quantity in cartLists) {//移除购物车中数量为0的对象
      if (cartLists[quantity].quantity == 0) {
        cartLists.splice(quantity, 1)
      }
    }
    this.setData({ cartLists: cartLists })//同时将所修改的数量保存到当前页面的购物车中
    //  console.log(cartLists)
    wx.setStorageSync('cartLists', cartLists);
    if (cartLists != '') {//当购物车不为空的时候，在计算总金额
      var totalMoneyArr = [];
      for (var index in this.data.cartLists) {
        totalMoneyArr.push(parseFloat(this.data.cartLists[index].quantity * this.data.cartLists[index].unitPrice).toFixed(2));
      }
      var totalMoney = totalMoneyArr.reduce(function (a, b) {
        return (parseFloat(a) + parseFloat(b)).toFixed(2);
      });
      that.setData({
        totalMoney: totalMoney
      });
    } else {
      wx.setStorageSync('cartLists', "");
      that.setData({
        hasCarts: true,
        noCarts: false
      })
    }
  },
  getCartInfo: function () {//将用户购买的商品以及用户信息发送到后台生成预支付订单
    //console.log(this.data.inputUser)
    var that = this;
    if (!this.data.inputUser) {
      wx.showModal({
        title: '检测到您暂无收货地址',
        content: '请点击确认到新增收货地址页面',
        showCancel: true,
        success: function (res) {
          if (res.confirm) {
            // determination = true;
            /* wx.navigateTo({
               url: '../addAddress/addAddress?direct=1',
             })*/
            that.chooseaddress();
          }
        }
      })
    } else {
      var directDetail = wx.getStorageSync('cartLists')
      // console.log(directDetail)
      var detailJson = [];
      var that = this;
      if (directDetail) {
        for (var i = 0; i < directDetail.length; i++) {
          detailJson.push({
            shop_id: directDetail[i].shopsId,
            product_id: directDetail[i].productId,
            totalPrices: directDetail[i].totalPrices,
            quantity: directDetail[i].quantity,
            unitPrice: directDetail[i].unitPrice,
          })
        }
      }
      //console.log(detailJson)
      wx.request({
        url: app.globalData.allUrl + "/goods/order",
        data: {
          userID: wx.getStorageSync('userid'),
          detailsjson: detailJson,
          totalMoney: that.data.totalMoney,
          addressID: {
            user: that.data.inputUser,
            phone: that.data.inputPhone,
            address: that.data.inputAddress,
          }
        },
        header: { 'content-type': "application/json" },
        method: 'POST',
        success: function (res) {
          console.log(res.data)
          wx.request({
            url: app.globalData.allUrl + "/wxpay/wx",
            data: {
              user_id: wx.getStorageSync('userid'),
              order_id: res.data,
              totalMoney: parseFloat(that.data.totalMoney),
            },
            header: { 'content-type': "application/json" },
            method: 'POST',
            success: function (res) {
              console.log(res.data)
              if (res.data.package) {
                var pay = res.data;
                wx.requestPayment({//如果从后台获取支付信息成功。则调用微信支付接口
                  timeStamp: pay.timeStamp,
                  nonceStr: pay.nonceStr,
                  package: pay.package,
                  signType: pay.signType,
                  paySign: pay.paySign,
                  success: function (res) {
                    // success
                    console.log(res)
                    wx.showToast({
                      title: '微信支付成功',
                      icon: 'success',
                      duration: 2000
                    })
                    wx.setStorageSync('cartLists', '')
                    setTimeout(function () {//两秒后跳转到我的页面
                      wx.switchTab({
                        url: '../my/my',
                        success: function (res) {
                          // success
                        }
                      })
                    }, 2000)
                  }, fail(res) {
                    console.log(res)
                  }
                })

              }
            }
          })
          // success

        }
      })
    }

  },
})